package com.learn.sunday.common.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;


@Slf4j(topic = "sunday-register")
@Component
@Configuration
@ConditionalOnMissingClass("org.springframework.cloud.client.discovery.EnableDiscoveryClient")
public class RegisterService {


    @Value("${sunday.register.url:http://127.0.0.1:8090/sunday/v1/register}")
    private String registerCenter;

    @Autowired
    private Environment environment;

    public RegisterService()
    {
        log.info("init register component!");
    }

    @Bean(name = "registerRestTemplate")
    @ConditionalOnClass(value = {RestTemplate.class})
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Resource(name = "registerRestTemplate")
    private RestTemplate restTemplate;

    @Scheduled(cron = "${sunday.register.schedules:0/30 * * * * ?}")
    public void register() throws UnknownHostException {
        log.info("url==={}",registerCenter);
        log.info("url==={}",registerCenter);
        log.info("url==={}",environment.getProperty("server.port"));
        log.info("url==={}",environment.getProperty("spring.application.name"));
        log.info("url==={}", InetAddress.getLocalHost());
        log.info("start register!");
        String s = restTemplate.postForObject(registerCenter, "", String.class);
        log.info("msg={}",s);
    }
}
